<!DOCTYPE HTML>
<html>
<script>
  safari.application.addEventListener('message',function(eve){
    if( eve.name === 'vimlike' ){
      var data = eve.message;
      var hintText = safari.extension.settings.getItem('hintText');
      var mytab = safari.application.activeBrowserWindow.activeTab;
      var pos = 0;
      if( data == 'previous' ){
        pos = -1;
      }else if( data == 'next'){
        pos = 1;
      }else if( data == 'close' ){
        VIMLIKE.regist.push(mytab.url);
        mytab.close();
        return;
      }else if( data == 'open' ){
        safari.application.activeBrowserWindow.openTab();
        return;
      }else if( data == 'reopen' ){
        if( VIMLIKE.regist.length > 0 ){
          var newTab = safari.application.activeBrowserWindow.openTab();
          newTab.url = VIMLIKE.regist.pop();
          newTab.page.dispatchMessage("hintText",hintText);
          setTimeout( function(){ newTab.activate(); }, 100 );
        }
      }else if( data == 'load' ){
        eve.target.page.dispatchMessage('hintText',hintText);
        return;
      }else if( data['background'] ){
        var url = data['background'];
        var newTab = safari.application.activeBrowserWindow.openTab();
        newTab.url = url;
        newTab.page.dispatchMessage("hintText",hintText);
      }
      var tabs = safari.application.activeBrowserWindow.tabs;
      var len = tabs.length;
      var lastPos = 0;

      if( tabs[len-1] == mytab && pos == 1){
        lastPos = 0;
      }else if( tabs[0] == mytab && pos == -1 ){
        lastPos = len -1;
      }else{
        while( len-- ){
          if( tabs[len] == mytab ){ //&& typeof tabs[len+pos] != 'undefined'){
              lastPos = len+pos;
              break;
            }
          }
      }
      tabs[lastPos].activate();
      tabs[lastPos].page.dispatchMessage("hintText",hintText);
    }

  },false);

safari.extension.settings.addEventListener('change',function(eve){
  if( eve.key == 'hintText' ){
    safari.application.activeBrowserWindow.activeTab.page.dispatchMessage('hintText', eve.newValue );
  }
},false );
var VIMLIKE = {};
VIMLIKE.regist = [];
</script>
<body>
</body>
</html>
